'use client'
/**
 * @license 敏捷之道软件
 * 商业用途必须获得书面授权
 * 侵权举报: ideaswork@qq.com
 * 法律依据:《计算机软件保护条例》第二十四条
 */
import { useEffect, useState } from 'react'
import { ProductCopy } from '@/types/Model'
import { useParams, useRouter } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import ReactMarkdown from 'react-markdown'
import mermaid from 'mermaid'
import rehypeRaw from 'rehype-raw'
import remarkGfm from 'remark-gfm'  
import { PrinterIcon } from 'lucide-react'

// 初始化 Mermaid 配置
const initMermaid = () => {
  mermaid.initialize({
    startOnLoad: false,
    securityLevel: 'loose',
    theme: 'default',
    fontFamily: 'inherit',
    flowchart: {
      curve: 'basis'
    }
  })
}

// 自定义代码块渲染组件
const CodeBlock = ({ node, inline, className, children, ...props }: any) => {
  const [svg, setSvg] = useState<string>('')
  const [error, setError] = useState<string>('')
  const [isPrinting, setIsPrinting] = useState(false)

  // 如果是行内代码或非 Mermaid 代码块，直接返回普通代码块
  if (inline || className !== 'language-mermaid') {
    return (
      <code
        className={`${className || ''}  rounded px-1.5 py-0.5 text-sm`}
        {...props}
      >
        {children}
      </code>
    )
  }



  useEffect(() => {
    const renderDiagram = async () => {
      try {
        // 精确匹配 mermaid 代码块
        if (className !== 'language-mermaid') return

        // 清除旧内容
        setSvg('')
        setError('')

        // 动态加载 mermaid
        mermaid.initialize({
          startOnLoad: false,
          securityLevel: 'loose',
          theme: 'default'
        })

        // 创建临时容器
        const tempDiv = document.createElement('div')
        tempDiv.style.position = 'absolute'
        tempDiv.style.left = '-9999px'
        document.body.appendChild(tempDiv)

        // 执行渲染
        const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`
        const { svg } = await mermaid.render(id, String(children).trim())
        setSvg(svg)
      } catch (err) {
        setError(`渲染失败: ${err instanceof Error ? err.message : '未知错误'}`)
      }
    }

    if (!isPrinting && className === 'language-mermaid') {
      renderDiagram()
    }
  }, [children, className, isPrinting])

  if (error) {
    return (
      <div className="p-3 my-4 border border-red-200 bg-red-50 text-red-600 rounded-md text-sm">
        <div className="font-medium">图表错误:</div>
        <div className="mt-1">{error}</div>
        <pre className="mt-2 p-2 bg-red-100 rounded text-xs overflow-auto">
          {children}
        </pre>
      </div>
    )
  }

  if (className?.includes('language-mermaid')) {
    return (
      <div className="mermaid-container my-6">
        {svg ? (
          <div 
            className="bg-white p-4 rounded-lg shadow-sm border"
            dangerouslySetInnerHTML={{ __html: svg }}
          />
        ) : (
          <div className="p-4 text-gray-500 bg-gray-50 rounded-lg">
            图表加载中...
          </div>
        )}
      </div>
    )
  }

  return (
    <code
      className={`${className} bg-gray-100 rounded px-1.5 py-0.5 text-sm`}
      {...props}
    >
      {children}
    </code>
  )
}

export default function CopyEditPage() {
  const { id } = useParams()
  const router = useRouter()
  const [copy, setCopy] = useState<ProductCopy | null>(null)
  const [loading, setLoading] = useState(true)

  // 初始化 Mermaid
  useEffect(() => {
    initMermaid()
    return () => {
      mermaid.initialize({ startOnLoad: false })
    }
  }, [])

  const fetchCopy = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy/${id}`, {
        headers: { 'Authorization': `Bearer ${token}` }
      })

      if (!response.ok) throw new Error('获取数据失败')
      
      const data = await response.json()
      setCopy(data)
      
      toast({
        title: '数据加载成功',
        description: '内容已准备好',
      })
    } catch (error) {
      console.error('获取数据错误:', error)
      toast({
        title: '加载失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      router.push('/copies')
    } finally {
      setLoading(false)
    }
  }

  const handlePrint = () => {
    // 确保使用 UTF-8 编码
    const originalTitle = document.title;
    document.title = "打印预览";
    
    // 添加 meta 标签确保编码
    const meta = document.createElement('meta');
    meta.setAttribute('charset', 'UTF-8');
    document.head.appendChild(meta);
  
    // 打印
    window.print();
  
    // 清理
    setTimeout(() => {
      document.title = originalTitle;
      meta.remove();
    }, 1000);
  };

  useEffect(() => {
    if (id) fetchCopy()
  }, [id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-blue-600"></div>
      </div>
    )
  }

  if (!copy) {
    return (
      <div className="p-4 text-center text-gray-500">
        未找到相关内容
      </div>
    )
  }

  return (
    <div className="w-full px-4 py-8 print:py-2">
      <div className="flex justify-end mb-8 print:hidden">
        <button
          className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors flex items-center gap-2"
          onClick={handlePrint}
        >
          <PrinterIcon className='w-4 h-4'></PrinterIcon>
          打印
        </button>
      </div>

      <article className="prose prose-slate lg:prose-lg max-w-5xl mx-auto print:prose-sm print:max-w-none prose-table:w-full
        prose-table:border-collapse
        prose-table:my-8
        prose-thead:bg-gray-50
        prose-th:p-3
        prose-th:border
        prose-th:border-gray-200
        prose-th:text-left
        prose-th:font-semibold
        prose-td:p-3
        prose-td:border
        prose-td:border-gray-200
        prose-tr:hover:bg-gray-50">
        <ReactMarkdown
          rehypePlugins={[rehypeRaw]}
          remarkPlugins={[remarkGfm]} 
          components={{
            code: CodeBlock,
            pre: ({ node, children, ...props }) => {
              // 如果是 mermaid 代码块，只返回 children
              if ((node?.children[0] as any)?.properties?.className?.includes('language-mermaid')) {
                return children
              }
              // 其他代码块正常渲染
              return <pre {...props}>{children}</pre>
            },
            img: ({ node, ...props }) => (
              <img 
               alt=''
                {...props} 
                className="rounded-lg border shadow-sm my-4 mx-auto"
                loading="lazy"
              />
            ),
        
          }}
        >
          {copy.md_content || ''}
        </ReactMarkdown>
      </article>

      <style jsx global>{`

     
        
        @media print {
          @page {
            margin: 2cm;
          }

          body * {
            visibility: hidden;
            font-family: 'AlibabaPuHuiTi';
           }

          article,
          article * {
            visibility: visible;
          }

          article {
            // 移除 fixed 定位
            position: relative;
            left: 0;
            top: 0;
            width: 100%;
            // 添加打印相关样式
            break-inside: auto;
            page-break-inside: auto;
          }

          // 添加分页控制
          h1, h2, h3 {
            break-before: auto;
            break-after: avoid;
          }

          table, figure, .mermaid-container {
            break-inside: avoid;
            page-break-inside: avoid;
            background: white !important;
          }
          
          .mermaid-container svg {
            max-height: 100% !important;
          }

          // 优化打印布局
          p, ul, ol {
            orphans: 3;
            widows: 3;
          }
        }
        
        .mermaid-container .label {
          font-family: var(--font-sans) !important;
        }
      `}</style>
    </div>
  )
}